<?php

namespace App\Models\Circle;

use App\Libraries\Easemob\Easemob;
use App\Models\BaseModel;
use Illuminate\Support\Facades\Auth;

class Circle extends BaseModel
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'updated_at',
    ];

    protected $table = 'circle';
    protected $dateFormat = 'U';

    /**
     * 关联用户信息
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user(){
        return $this->belongsTo('App\Models\User\User', 'user_id', 'user_id');
    }

    /**
     * 关联积分
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function points(){
        return $this->hasOne('App\Models\User\UserPoint', 'user_id', 'user_id');
    }

    /**
     * 朋友圈列表
     * @param $page
     * @param $size
     * @param $user_id
     * @return mixed
     */
    public function circles($page, $size, $user_id){
        if(empty($user_id)){
            $user_ids = [Auth::id()];
            $friends = Easemob::singleton()->showFriends(Auth::id());
            if(!isset($friends['error']) && is_array($friends['data'])){
                $user_ids = array_merge($user_ids, $friends['data']);
            }
            $sql = $this->whereIn('user_id', $user_ids)
                ->withOnly('user', ['user_id', 'nickname', 'cover', 'vip_level']);
        }else{
            $sql = $this->where('user_id', $user_id);
        }
        $data['list'] = $sql->with('points')->where('status', 1)
            ->forPage($page, $size+1)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();
        $data['next_page'] = $page + 1;
        $data['page_size'] = $size;
        return $this->after($data);
    }
}
